# coding=UTF-8
from google.appengine.ext.db import djangoforms as forms
from models import Post
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic.list_detail import object_list
from google.appengine.api import users
from django.http import HttpResponseRedirect

import authorized

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        exclude = ['author']

@authorized.role("user")
def add_post(request):
    if request.method == 'GET':
        form = PostForm()
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save()
            post.author = users.get_current_user()
            post.put()
            return HttpResponseRedirect('/post/add/')
        
    return render_to_response('blog/add_post.html',
                              {'form': form},
                              context_instance=RequestContext(request))

   
def list_post(request):
#    posts = Post.all().order('-create_time')
##    if (not is_admin()):
#    posts = posts.filter("is_published", True)
##extra_context={'is_admin': is_admin()}
#        
#    return object_list(request, queryset=posts, allow_empty=True,
#                            template_name='blog/list_post.html',
#                            extra_context=None,
#                            paginate_by=20)
    posts = Post.all().order('-create_time')
    posts = posts.filter("is_published", True)
    dict={'posts':posts,
          'paginate_by':20,
                    
          }
    return render_to_response('blog/list_post.html',
                              dict)
    

